﻿using System;
using System.Collections.Generic;
using System.Data;
using System.IO;
using System.Linq;
using System.Text;
using EMoney.IStock.Client.DataAccess;
using EMoney.IStock.Client.Framework;
using EMoney.IStock.Client.Models.QQ;
using ThinkDev.Logging;

namespace EMoney.IStock.Client.Business.QQ
{
    /// <summary>
    /// 高手聚焦业务处理类
    /// </summary>
    public class FocusBll
    {
        FocusStockDal dal = new FocusStockDal();
        string keyPre = "EMoney:IStock:Client.Business.QQ.FocusBll.";

        /// <summary>
        /// 获取所有内网账号
        /// </summary>
        /// <returns></returns>
        public List<string> GetAllPower()
        {
            string key = keyPre + "IsAllPower";
            List<string> list = JRPTCommCache.GetCache<List<string>>(key);
            if (list == null || list.Count <= 0)
            {
                string path = System.AppDomain.CurrentDomain.BaseDirectory + "App_Data\\allpower.txt";
                string[] lines = File.ReadAllLines(path, Encoding.GetEncoding("utf-8"));
                list = new List<string>();
                foreach (var line in lines)
                {
                    if (line != null)
                    {
                        list.Add(line.Trim());
                    }
                }
                if (list != null && list.Count > 0)
                {
                    JRPTCommCache.AddCache<List<string>>(key, list, 60 * 24 * 30);
                }
            }
            return list;
        }

        /// <summary>
        /// 获取聚焦个股数据
        /// </summary>
        /// <param name="startDate">大于等于开始时间</param>
        /// <param name="endDate">小于结束时间</param>
        /// <param name="isCache">是否读取缓存</param>
        /// <returns></returns>
        public List<TB_FocusStock> GetFocusStockList(DateTime startDate, DateTime endDate, bool isCache = true)
        {
            string key = keyPre + "GetFocusStockList" + startDate.ToString() + endDate.ToString();
            List<TB_FocusStock> list = JRPTCommCache.GetCache<List<TB_FocusStock>>(key);
            if (list == null || list.Count <= 0 || !isCache)
            {
                try
                {
                    list = dal.GetFocusStockList(startDate, endDate);
                }
                catch (Exception ex)
                {
                    LogManager.DefaultLogger.Error(LogConvert.ParseWebEx(ex), "TradeBll->GetFocusStockList 读取聚焦个股发生异常！");
                }
                if (list != null && list.Count > 0)
                {
                    JRPTCommCache.AddCache<List<TB_FocusStock>>(key, list);
                }
            }
            return list;
        }

        /// <summary>
        /// 获取聚焦板块数据
        /// </summary>
        /// <param name="startDate">大于等于开始时间</param>
        /// <param name="endDate">小于结束时间</param>
        /// <param name="isCache">是否读取缓存</param>
        /// <returns></returns>
        public List<TB_FocusBlock> GetFocusBlockList(DateTime startDate, DateTime endDate, bool isCache = true)
        {
            string key = keyPre + "GetFocusBlockList" + startDate.ToString() + endDate.ToString();
            List<TB_FocusBlock> list = JRPTCommCache.GetCache<List<TB_FocusBlock>>(key);
            if (list == null || list.Count <= 0 || !isCache)
            {
                try
                {
                    list = dal.GetFocusBlockList(startDate, endDate);
                }
                catch (Exception ex)
                {
                    LogManager.DefaultLogger.Error(LogConvert.ParseWebEx(ex), "TradeBll->GetFocusBlockList 读取聚焦板块发生异常！");
                }
                if (list != null && list.Count > 0)
                {
                    JRPTCommCache.AddCache<List<TB_FocusBlock>>(key, list);
                }
            }
            return list;
        }

        /// <summary>
        /// 根据用户ID获取用户信息
        /// </summary>
        /// <param name="uid">用户UID</param>
        /// <param name="isCache">是否读取缓存</param>
        /// <returns></returns>
        public TB_JRPT_UserInfo GetUserInfo(string uid, bool isCache = true)
        {
            string key = keyPre + "GetUserInfo" + uid;
            TB_JRPT_UserInfo user = JRPTCommCache.GetCache<TB_JRPT_UserInfo>(key);
            if (user == null || !isCache)
            {
                try
                {
                    user = dal.GetUserInfo(uid);
                }
                catch (Exception ex)
                {
                    LogManager.DefaultLogger.Error(LogConvert.ParseWebEx(ex), "TradeBll->GetUserInfo 读取用户信息发生异常！");
                }
                if (user != null)
                {
                    JRPTCommCache.AddCache<TB_JRPT_UserInfo>(key, user);
                }
            }
            return user;
        }

        /// <summary>
        /// 添加用户信息
        /// </summary>
        /// <param name="user"></param>
        /// <returns></returns>
        public TB_JRPT_UserInfo AddUserInfo(TB_JRPT_UserInfo user, ref string msg)
        {
            int re = dal.AddUserInfo(user, ref msg);
            if (re > 0)
            {
                user = GetUserInfo(user.UserID, false);
            }
            else
            {
                if (string.IsNullOrEmpty(msg))
                    msg = "QQ号码绑定失败";
            }
            return user;
        }

        /// <summary>
        /// 更新聚焦个股
        /// </summary>
        public static void TaskUpdateFocusStockList()
        {
            //判断是否是交易时间
            if (IsTradeTime())
            {
                LogManager.WebApiLogger.InfoFormat("FocusBll->TaskUpdateFocusStockList 更新聚焦个股数据 StartTime:{0}", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss fff"));

                FocusBll bll = new FocusBll();
                bll.UpdateRankingList();

                LogManager.WebApiLogger.InfoFormat("FocusBll->TaskUpdateFocusStockList 更新聚焦个股数据 EndTime:{0}", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss fff"));
            }
        }

        /// <summary>
        /// 判断当前时间是否是交易时间
        /// </summary>
        /// <returns></returns>
        static bool IsTradeTime()
        {
            bool bz = false;
            if (ConfigHelper.IsOnline == "0")
                return true;
            DateTime now = DateTime.Now;
            if (TradeDateBll.IsTradeDate(now))
            {
                if ((now >= Convert.ToDateTime(now.ToString("yyyy-MM-dd") + " 09:30") && now <= Convert.ToDateTime(now.ToString("yyyy-MM-dd") + " 16:00")))
                {
                    bz = true;
                }
            }
            return bz;
        }

        /// <summary>
        /// 更新排行榜数据
        /// </summary>
        /// <returns></returns>
        void UpdateRankingList()
        {
            RankBll rbll = new RankBll();
            TradeBll tbll = new TradeBll();

            DataTable mycsvdt = new DataTable();
            DataColumn mydc;
            //创建表
            mydc = new DataColumn("deal_count");
            mycsvdt.Columns.Add(mydc);

            mydc = new DataColumn("total");
            mycsvdt.Columns.Add(mydc);

            mydc = new DataColumn("c_time");
            mycsvdt.Columns.Add(mydc);

            mydc = new DataColumn("stock_code");
            mycsvdt.Columns.Add(mydc);

            mydc = new DataColumn("trade_direction");
            mycsvdt.Columns.Add(mydc);

            mydc = new DataColumn("stock_name");
            mycsvdt.Columns.Add(mydc);

            mydc = new DataColumn("trade_price");
            mycsvdt.Columns.Add(mydc);

            mydc = new DataColumn("trade_count");
            mycsvdt.Columns.Add(mydc);

            mydc = new DataColumn("deal_price");
            mycsvdt.Columns.Add(mydc);

            mydc = new DataColumn("dtype");
            mycsvdt.Columns.Add(mydc);

            mydc = new DataColumn("user_qq");
            mycsvdt.Columns.Add(mydc);

            DataRow mydr;
            List<string> list = new List<string>();

            List<Rank> alst = new List<Rank>();//总排行榜
            List<Rank> wlst = new List<Rank>();//周排行榜
            List<Rank> dlst = new List<Rank>();//日排行榜
            try
            {
                alst = rbll.GetRankLst();
            }
            catch (Exception ex)
            {
                LogManager.WebApiLogger.Error(LogConvert.ParseWebEx(ex), "RankBll->GetRankLst 获取总排行榜数据发生异常！");
                alst = new List<Rank>();
            }

            try
            {
                wlst = rbll.GetRankWeekLst();
                alst = alst.Union(wlst).ToList();
            }
            catch (Exception ex)
            {
                LogManager.WebApiLogger.Error(LogConvert.ParseWebEx(ex), "RankBll->GetRankWeekLst 获取周排行榜数据发生异常！");
                wlst = new List<Rank>();
            }

            try
            {
                dlst = rbll.GerRankDayLst();
                alst = alst.Union(dlst).ToList();
            }
            catch (Exception ex)
            {
                LogManager.WebApiLogger.Error(LogConvert.ParseWebEx(ex), "RankBll->GerRankDayLst 获取日排行榜数据发生异常！");
                dlst = new List<Rank>();
            }

            if (alst != null)
            {
                list = alst.Select(x => x.user_qq).Distinct().ToList();
            }

            string key = keyPre + "GetDealOrdersMaxID";
            long lastID = JRPTCommCache.GetCache<long>(key);

            if (lastID <= 0)
            {
                lastID = GetDealOrdersMaxID(lastID);
            }

            foreach (var c in list)
            {
                string userQQ = c;

                //读取成交单信息
                DealOrders rlst = new DealOrders();
                try
                {
                    rlst = tbll.GetDealOrders(userQQ, DateTime.Now.ToString("yyyyMMdd"), DateTime.Now.ToString("yyyyMMdd"));
                }
                catch (Exception ex)
                {
                    LogManager.WebApiLogger.Error(LogConvert.ParseWebEx(ex), "TradeBll->GetDealOrders 读取成交单信息发生异常！[qq={0}]", userQQ);
                }
                if (rlst != null && rlst.data != null && rlst.data.Count > 0)
                {
                    foreach (var deal in rlst.data)
                    {
                        //填充数据并加入到datatable中
                        mydr = mycsvdt.NewRow();

                        mydr["deal_count"] = deal.deal_count;
                        mydr["total"] = deal.total;
                        mydr["c_time"] = deal.c_time;
                        mydr["stock_code"] = deal.stock_code;
                        mydr["trade_direction"] = deal.trade_direction;
                        mydr["stock_name"] = deal.stock_name;
                        mydr["trade_price"] = deal.trade_price;
                        mydr["trade_count"] = deal.trade_count;
                        mydr["deal_price"] = deal.deal_price;
                        mydr["dtype"] = deal.dtype;
                        mydr["user_qq"] = userQQ;

                        mycsvdt.Rows.Add(mydr);
                    }
                }
            }
            if (mycsvdt != null && mycsvdt.Rows.Count > 0)
            {
                //交易数据存入数据库
                AddDealOrders(mycsvdt);
                //更新聚焦数据
                int re = AddFocusStock(lastID);
                if (re > 0)
                {
                    GetDealOrdersMaxID(lastID);
                    //更新缓存
                    GetFocusStockList(DateTime.Now.Date.AddDays(-1), DateTime.Now.Date.AddDays(1), false);
                    //更新缓存
                    GetFocusBlockList(DateTime.Now.Date.AddDays(-1), DateTime.Now.Date.AddDays(1), false);
                }
            }
        }

        /// <summary>
        /// 根据开始日期获取最大入库ID
        /// </summary>
        /// <param name="lastID">上一次最大更新ID</param>
        /// <returns></returns>
        long GetDealOrdersMaxID(long lastID)
        {
            string key = keyPre + "GetDealOrdersMaxID";

            long now = 0;
            try
            {
                now = dal.GetDealOrdersMaxID(lastID);
            }
            catch (Exception ex)
            {
                LogManager.WebApiLogger.Error(LogConvert.ParseWebEx(ex), "TradeBll->GetDealOrdersMaxID 根据开始日期获取最大入库ID发生异常！");
            }
            JRPTCommCache.AddCache<long>(key, now);

            return now;
        }

        /// <summary>
        /// 批量更新聚焦数据
        /// </summary>
        /// <param name="lastDate">上一次最大更新ID</param>
        /// <returns></returns>
        int AddFocusStock(long lastID)
        {
            try
            {
                return dal.AddFocusStock(lastID);
            }
            catch (Exception ex)
            {
                LogManager.WebApiLogger.Error(LogConvert.ParseWebEx(ex), "TradeBll->AddFocusStock 更新聚焦数据发生异常！");
            }
            return -1;
        }

        /// <summary>
        /// 批量更新交易数据
        /// </summary>
        /// <param name="dt"></param>
        void AddDealOrders(DataTable dt)
        {
            try
            {
                dal.AddDealOrders(dt);
            }
            catch (Exception ex)
            {
                LogManager.WebApiLogger.Error(LogConvert.ParseWebEx(ex), "TradeBll->AddDealOrders 更新交易信息发生异常！");
            }
        }
    }
}
